package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.entity.TbOrdersRefund;
import com.robotserver.orders.jobs.xxljob.instance.AliPushOrderClient;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.mapper.TbOrdersRefundMapper;
import com.robotserver.orders.param.TbOrderRefundSyncParam;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.param.biz.TbOrderPullParam;
import com.robotserver.orders.service.*;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.robotserver.orders.vo.biz.PageVO;
import com.robotserver.orders.vo.biz.TbOrderRefundVO;
import com.robotserver.orders.vo.biz.TbOrderVO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/11/13 17:20
 * @Description:
 */
@Service
public class TbOrderRefundServiceImpl implements TbOrderRefundService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderRefundServiceImpl.class);

    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private AlimmTokensMapper alimmTokensMapper;
    @Autowired
    private TbPayOrderSyncService tbPayOrderSyncService;
    @Autowired
    private TbSettleOrderSyncService tbSettleOrderSyncService;
    @Autowired
    private TbReceivingOrderSyncService tbReceivingOrderSyncService;
    @Autowired
    private TbOrdersRefundMapper tbOrdersRefundMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private TbOrderRefundSyncService tbOrderRefundSyncService;
    @Value("${taobao.sdk.url}")
    private String taobaoSdkUrl;

    @Async("taskExecutor")
    @Override
    public void syncOrder_producer(TbOrderRefundSyncParam tbOrderRefundSyncParam) {
        try {
            //查询所有有效期内的阿里妈妈tokens
            List<AlimmTokens> alimmTokensList = alimmTokensMapper.getAllTokens(DateUtil.getNowTime());
            //往redis队列中塞阿里妈妈tokens
            for (AlimmTokens alimmTokens : alimmTokensList) {
                alimmTokens.setBeginTime(tbOrderRefundSyncParam.getBegin_time());
                alimmTokens.setEndTime(tbOrderRefundSyncParam.getEnd_time());
                alimmTokens.setType(tbOrderRefundSyncParam.getType());
                alimmTokens.setOrderScene(tbOrderRefundSyncParam.getBizType());
                alimmTokens.setRedisQueueKey(tbOrderRefundSyncParam.getRedisQueueKey());
                //对象转成JSON字符串，保存到redis队列中
                String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                redisTemplate.opsForList().leftPush(tbOrderRefundSyncParam.getRedisQueueKey(), alimmTokensStr);
                //logger.info("-------------往redis中推入淘宝联盟的普通账号付款订单tokens------alimmTokensStr=" + alimmTokensStr);
                Thread.sleep(1); //0毫秒调用一次
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async("taskExecutor")
    @Override
    public void syncOrder_consumer(TbOrderRefundSyncParam tbOrderRefundSyncParam) {
        String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
        String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");
        TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret,"json", 120000,240000);

        //导购联盟不需要下载维权订单（导购app不支持）
        String tb_appkey_dg = sysSettingMapper.getByKey("tb_appkey_dg");
        String tb_appsecret_dg = sysSettingMapper.getByKey("tb_appsecret_dg");
        TaobaoClient client_dg = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey_dg, tb_appsecret_dg,"json", 120000,240000);

        while (true) {
            try {
                //从redis队列中获取联盟
                Object alimmTokensObject = redisTemplate.opsForList().rightPop(tbOrderRefundSyncParam.getRedisQueueKey());
                if (alimmTokensObject != null) {
                    //鉴于client是单例模式，估计初始化项目时，建立连接，创建单例模式
                    //TaobaoClient client = AliPushOrderClient.getTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);
                    //logger.info("tbtoken redis pop:" + alimmTokensObject.toString());

                    AlimmTokens alimmTokens = JSONObject.parseObject(alimmTokensObject.toString(),AlimmTokens.class);
                    //封装分段时间查询参数
                    List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderRefundTimeScope(alimmTokens.getBeginTime(),alimmTokens.getEndTime());

                    if(alimmTokens.getTurnlink() != null && alimmTokens.getTurnlink().intValue() == 1 ){//导购的联盟，需要导购的工具商APP
                        tbOrderRefundSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens,client_dg);
                    }else{
                        tbOrderRefundSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens,client);
                    }

                    Thread.sleep(20); //20毫秒调用一次
                }else{
                    // 没有需要处理的数据了
                    logger.info("-------------------------淘宝维权订单已经消费完成---------------");
                    break;
                }
            } catch (Exception e) {
                logger.error("tb redis pop token err:" + e);
                continue;
            }
        }
    }

    @Override
    public TbOrderRefundVO getOrderList(TbOrderPullParam param) {
        List<TbOrdersRefund> list = tbOrdersRefundMapper.getOrderList(param);
        TbOrderRefundVO tbOrderRefundVO = new TbOrderRefundVO();
        tbOrderRefundVO.setRecords(list);
        return tbOrderRefundVO;
    }


    @Async("taskExecutor")
    @Override
    public void remotePull(TbOrderRefundSyncParam tbOrderRefundSyncParam) {
        try {
            String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
            String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");

            //鉴于client是单例模式，估计初始化项目时，建立连接，创建单例模式
            TaobaoClient client = AliPushOrderClient.getTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);

            //导购联盟不需要下载维权订单（导购app不支持）
            String tb_appkey_dg = sysSettingMapper.getByKey("tb_appkey_dg");
            String tb_appsecret_dg = sysSettingMapper.getByKey("tb_appsecret_dg");
            TaobaoClient client_dg = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey_dg, tb_appsecret_dg,"json", 120000,240000);


            //封装分段时间查询参数
            List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderRefundTimeScope(tbOrderRefundSyncParam.getBegin_time(), tbOrderRefundSyncParam.getEnd_time());

            //从参数表对象中获取token信息
            //渠道维权订单
            AlimmTokens alimmTokens_channel = new AlimmTokens();
            alimmTokens_channel.setBeginTime(tbOrderRefundSyncParam.getBegin_time());
            alimmTokens_channel.setEndTime(tbOrderRefundSyncParam.getEnd_time());
            alimmTokens_channel.setType(tbOrderRefundSyncParam.getType());
            alimmTokens_channel.setUserId(tbOrderRefundSyncParam.getUserId());
            alimmTokens_channel.setUserName(tbOrderRefundSyncParam.getUserName());
            alimmTokens_channel.setAccessToken(tbOrderRefundSyncParam.getAccessToken());
            alimmTokens_channel.setOrderScene(1L);
            alimmTokens_channel.setRedisQueueKey(CacheKey.tbOrderRefundQueue);
            alimmTokens_channel.setTurnlink(tbOrderRefundSyncParam.getTurnlink());

            if(tbOrderRefundSyncParam.getTurnlink() != null && tbOrderRefundSyncParam.getTurnlink().intValue() == 1 ){//导购的联盟，需要导购的工具商APP
                tbOrderRefundSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens_channel,client_dg);
            }else{
                tbOrderRefundSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens_channel,client);
            }

//
//            Thread.sleep(200); //200毫秒调用一次
//
//            //会员维权订单
//            AlimmTokens alimmTokens_sid = new AlimmTokens();
//            alimmTokens_sid.setBeginTime(tbOrderRefundSyncParam.getBegin_time());
//            alimmTokens_sid.setEndTime(tbOrderRefundSyncParam.getEnd_time());
//            alimmTokens_sid.setType(tbOrderRefundSyncParam.getType());
//            alimmTokens_sid.setUserId(tbOrderRefundSyncParam.getUserId());
//            alimmTokens_sid.setUserName(tbOrderRefundSyncParam.getUserName());
//            alimmTokens_sid.setAccessToken(tbOrderRefundSyncParam.getAccessToken());
//            alimmTokens_sid.setOrderScene(2L);
//            alimmTokens_sid.setRedisQueueKey(CacheKey.tbOrderRefundQueue);
//            tbOrderRefundSyncService.threadSyncOrder_consumer(tbkOrderTimeVOList,alimmTokens_sid,client);

        } catch (Exception e) {
            logger.error("----tb refund orders remotePull err: token={}" + tbOrderRefundSyncParam.getAccessToken());
        }
    }

}
